<template>
  <PageContainer
    title="装车管理"
    :actions="pageActions"
    :columns="columns"
    :data-source="orderList"
    :loading="loading"
    :table-scroll="tableScroll"
    :pagination-data="pagination"
    :row-selection="rowSelection"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 筛选条件 -->
    <template #filter-items>
      <a-form-item label="运单编号">
        <a-input
          v-model:value="queryParams.orderNo"
          placeholder="输入运单编号"
          allowClear
        />
      </a-form-item>

      <a-form-item label="货物编码">
        <a-input
          v-model:value="queryParams.goodsCode"
          placeholder="输入货物编码"
          allowClear
        />
      </a-form-item>

      <a-form-item
        v-if="
          userStore.userInfo?.role === 'SUPER_ADMIN' &&
          userStore.userInfo?.siteId === null
        "
        label="发货站点"
      >
        <a-select
          v-model:value="queryParams.departureSiteId"
          placeholder="全部发货站点"
          allowClear
          :loading="siteLoading"
        >
          <a-select-option
            v-for="site in siteOptions"
            :key="site.id"
            :value="site.id"
          >
            {{ site.siteName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="到货站点">
        <a-select
          v-model:value="queryParams.arrivalSiteId"
          placeholder="全部到货站点"
          allowClear
          :loading="siteLoading"
        >
          <a-select-option
            v-for="site in siteOptions"
            :key="`arrival-${site.id}`"
            :value="site.id"
          >
            {{ site.siteName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="订单状态">
        <a-select
          v-model:value="queryParams.orderStatus"
          placeholder="全部状态"
          allowClear
          :options="statusOptions"
        />
      </a-form-item>

      <a-form-item label="装车时间" class="col-span-2">
        <a-range-picker
          v-model:value="loadedAtRange"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['开始时间', '结束时间']"
        />
      </a-form-item>
      <a-form-item label="司机姓名">
        <a-input
          v-model:value="queryParams.driverName"
          placeholder="输入司机姓名"
          allowClear
        />
      </a-form-item>

      <a-form-item label="司机电话">
        <a-input
          v-model:value="queryParams.driverPhone"
          placeholder="输入司机电话"
          allowClear
        />
      </a-form-item>

      <a-form-item label="车牌号">
        <a-input
          v-model:value="queryParams.vehiclePlate"
          placeholder="输入车牌号"
          allowClear
        />
      </a-form-item>

      <a-form-item label="货物名称">
        <a-input
          v-model:value="queryParams.goodsName"
          placeholder="输入货物名称"
          allowClear
        />
      </a-form-item>

      <a-form-item label="关键字">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="姓名/电话/单号等关键字"
          allowClear
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'orderInfo'">
        <div class="order-info">
          <div class="order-no">{{ record.orderNo }}</div>
          <div class="order-meta">编码：{{ record.goodsCode || "-" }}</div>
        </div>
      </template>

      <template v-else-if="column.key === 'sites'">
        <div class="site-route">
          <span>{{ record.departureSiteName || "未填写" }}</span>
          <ArrowRightOutlined class="site-arrow" />
          <span>{{ record.arrivalSiteName || "未填写" }}</span>
        </div>
      </template>

      <template v-else-if="column.key === 'receiver'">
        <div class="contact-block">
          <span class="contact-name">{{ record.receiverName || "-" }}</span>
          <span class="contact-phone">{{ record.receiverPhone || "-" }}</span>
        </div>
      </template>

      <template v-else-if="column.key === 'sender'">
        <div class="contact-block">
          <span class="contact-name">{{ record.senderName || "-" }}</span>
          <span class="contact-phone">{{ record.senderPhone || "-" }}</span>
        </div>
      </template>

      <template v-else-if="column.key === 'goods'">
        <div class="goods-info">
          <span class="goods-name">{{ record.goodsName || "-" }}</span>
          <span class="goods-detail">{{ record.goodsPieces || 0 }}件</span>
        </div>
      </template>

      <template v-else-if="column.key === 'driver'">
        <div v-if="record.driverName || record.driverPhone" class="driver-info">
          <div class="driver-name">{{ record.driverName || "-" }}</div>
          <div v-if="record.driverPhone" class="driver-phone">
            {{ record.driverPhone }}
          </div>
        </div>
        <span v-else class="text-secondary">未分配</span>
      </template>

      <template v-else-if="column.key === 'vehicle'">
        <div v-if="record.vehiclePlate" class="vehicle-info">
          <div class="vehicle-plate">{{ record.vehiclePlate }}</div>
        </div>
        <span v-else class="text-secondary">-</span>
      </template>

      <template v-else-if="column.key === 'loadedAt'">
        <span>{{ formatDateTime(record.loadedAt) || "-" }}</span>
      </template>

      <template v-else-if="column.key === 'orderStatus'">
        <a-tag :color="getStatusMeta(record.orderStatus)?.color">
          {{ getStatusMeta(record.orderStatus)?.label || record.orderStatus }}
        </a-tag>
      </template>

      <template v-else-if="column.key === 'createTime'">
        <span>{{ formatDateTime(record.createTime) }}</span>
      </template>

      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button
            v-if="record.orderStatus === 'RECEIVED'"
            type="link"
            size="small"
            v-permission="'order:load'"
            @click="openLoadModal([record.id])"
            >装车</a-button
          >
          <a-button
            v-if="record.orderStatus === 'LOADED'"
            type="link"
            size="small"
            danger
            v-permission="'order:unload'"
            @click="confirmUnload([record.id])"
            >卸车</a-button
          >
        </a-space>
      </template>
    </template>
  </PageContainer>

  <!-- 装车弹窗 -->
  <a-modal
    v-model:open="showLoadModal"
    title="运单装车"
    @ok="confirmLoad"
    @cancel="closeLoadModal"
    :confirmLoading="loadSubmitting"
  >
    <a-form layout="vertical">
      <a-form-item>
        <a-radio-group v-model:value="useTempVehicle">
          <a-radio :value="false">选择公司车辆</a-radio>
          <a-radio :value="true">使用临时车辆</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="!useTempVehicle" label="公司车辆" required>
        <a-select
          v-model:value="loadForm.vehicleId"
          placeholder="输入车牌号搜索"
          show-search
          :filter-option="false"
          :loading="vehicleLoading"
          @search="handleVehicleSearch"
          @focus="handleVehicleFocus"
        >
          <a-select-option
            v-for="v in vehicleOptions"
            :key="v.id"
            :value="v.id"
          >
            {{ v.plateNumber }} - {{ v.ownerName || "未填写" }}（{{
              v.ownerPhone || "未填写"
            }}）
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-else label="车牌号" required>
        <a-input
          v-model:value="loadForm.vehicleNo"
          :maxlength="20"
          placeholder="请输入车牌号，如 沪A12345"
        />
      </a-form-item>

      <a-form-item v-if="useTempVehicle" label="车主姓名" required>
        <a-input
          v-model:value="loadForm.driverName"
          :maxlength="50"
          placeholder="请输入车主姓名"
        />
      </a-form-item>

      <a-form-item v-if="useTempVehicle" label="联系电话" required>
        <a-input
          v-model:value="loadForm.driverPhone"
          :maxlength="20"
          placeholder="请输入车主联系电话"
        />
      </a-form-item>

      <a-form-item v-if="useTempVehicle" label="备注">
        <a-textarea
          v-model:value="loadForm.remark"
          :rows="2"
          :maxlength="200"
          placeholder="可填写临时车辆说明"
        />
      </a-form-item>

      <a-form-item label="装车时间">
        <a-date-picker
          v-model:value="loadForm.loadedAt"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </a-form-item>

      <div class="hint">
        本次将对 <strong>{{ pendingIds.length }}</strong> 条运单执行装车。
      </div>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { ArrowRightOutlined, CarOutlined } from "@ant-design/icons-vue";
import PageContainer from "@/components/business/PageContainer.vue";
import { useUserStore } from "@/stores/user";
import { getOrderList, orderLoad, orderUnload } from "@/api/tenant/order";
import { getSiteList } from "@/api/tenant/site";
import { getVehicleList } from "@/api/tenant/vehicle";
import type { Order, OrderQueryParams, OrderStatus } from "@/types/order";
import { ORDER_STATUS_CONFIG } from "@/types/order";
import type { Site } from "@/types/site";
import type { Vehicle } from "@/types/vehicle";
import type { Dayjs } from "dayjs";
import dayjs from "dayjs";
import { formatDateTime } from "@/utils/format";

const userStore = useUserStore();

const queryParams = reactive<OrderQueryParams>({
  current: 1,
  size: 10,
  orderStatus: undefined,
  orderNo: "",
  goodsCode: "",
  departureSiteId: undefined,
  arrivalSiteId: undefined,
  driverName: "",
  driverPhone: "",
  vehiclePlate: "",
  goodsName: "",
  keyword: "",
});

const loadedAtRange = ref<[Dayjs, Dayjs] | null>(null);

const orderList = ref<Order[]>([]);
const loading = ref(false);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ["10", "20", "50", "100"],
});

const columns = [
  { title: "运单信息", key: "orderInfo", fixed: "left" as const, width: 200 },
  { title: "站点路线", key: "sites", width: 220 },
  { title: "收货人/电话", key: "receiver", width: 140 },
  { title: "发货人/电话", key: "sender", width: 140 },
  { title: "货物信息", key: "goods", width: 140 },
  { title: "收货司机", key: "driver", width: 140 },
  { title: "运输车辆", key: "vehicle", width: 120 },
  { title: "装车时间", key: "loadedAt", width: 180 },
  {
    title: "状态",
    dataIndex: "orderStatus",
    key: "orderStatus",
    width: 100,
    align: "center" as const,
  },
  { title: "创建时间", dataIndex: "createTime", key: "createTime", width: 180 },
  {
    title: "操作",
    key: "action",
    fixed: "right" as const,
    width: 180,
    align: "center" as const,
  },
];

const tableScrollX = computed(() =>
  columns.reduce(
    (sum, col: any) => sum + (col.width ? Number(col.width) : 0),
    0
  )
);
const tableScroll = computed(() => ({
  x: tableScrollX.value,
  y: "calc(100vh - 480px)",
}));

// 多选
const selectedRowKeys = ref<number[]>([]);
const rowSelection = reactive({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: (string | number)[]) => {
    selectedRowKeys.value = keys as number[];
    rowSelection.selectedRowKeys = selectedRowKeys.value;
  },
});

const pageActions = computed(() => [
  {
    key: "batchLoad",
    label: "批量装车",
    type: "primary" as const,
    icon: CarOutlined,
    permission: "order:load",
    onClick: () => openLoadModal(selectedRowKeys.value),
  },
  {
    key: "batchUnload",
    label: "批量卸车",
    danger: true,
    permission: "order:unload",
    onClick: () => confirmUnload(selectedRowKeys.value),
  },
]);

const siteOptions = ref<Site[]>([]);
const siteLoading = ref(false);
const vehicleOptions = ref<Vehicle[]>([]);
const vehicleLoading = ref(false);

const statusOptions = Object.entries(ORDER_STATUS_CONFIG).map(
  ([value, meta]) => ({ label: meta.label, value: value as OrderStatus })
);
const getStatusMeta = (status?: OrderStatus) =>
  status ? ORDER_STATUS_CONFIG[status] : undefined;

const fetchOrderList = async () => {
  loading.value = true;
  try {
    const params: Record<string, any> = {
      ...queryParams,
      current: pagination.current,
      size: pagination.pageSize,
    };

    // 站点范围：当前站点默认只看本站发货
    const currentSiteId = userStore.userInfo?.siteId;
    if (currentSiteId) {
      params.departureSiteId = currentSiteId;
    }

    if (loadedAtRange.value && loadedAtRange.value.length === 2) {
      params.loadedAtStart = loadedAtRange.value[0].format(
        "YYYY-MM-DD HH:mm:ss"
      );
      params.loadedAtEnd = loadedAtRange.value[1].format("YYYY-MM-DD HH:mm:ss");
    }

    const res = await getOrderList(params as any);
    const data = res.data as any;
    orderList.value = data?.records ?? [];
    pagination.total = data?.total ?? 0;
  } catch (e) {
    console.error("获取装车列表失败", e);
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchOrderList();
};
const handleReset = () => {
  Object.assign(queryParams, {
    orderStatus: undefined,
    orderNo: "",
    goodsCode: "",
    departureSiteId: undefined,
    arrivalSiteId: undefined,
    driverName: "",
    driverPhone: "",
    vehiclePlate: "",
    goodsName: "",
    keyword: "",
  });
  loadedAtRange.value = null;
  pagination.current = 1;
  fetchOrderList();
};
const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchOrderList();
};

// 站点与车辆数据
const loadSites = async () => {
  siteLoading.value = true;
  try {
    const res = await getSiteList();
    siteOptions.value = (res.data as any) ?? [];
  } catch (e) {
    console.error("获取站点失败", e);
  } finally {
    siteLoading.value = false;
  }
};

let vehicleSearchTimer: any = null;
const searchVehicles = async (keyword: string = "") => {
  vehicleLoading.value = true;
  try {
    const res = await getVehicleList({
      current: 1,
      size: 50,
      keyword: keyword.trim(),
    });
    const data = res.data as any;
    vehicleOptions.value = data.records || [];
  } catch (e) {
    console.error("获取车辆失败", e);
  } finally {
    vehicleLoading.value = false;
  }
};
const handleVehicleSearch = (value: string) => {
  if (vehicleSearchTimer) clearTimeout(vehicleSearchTimer);
  vehicleSearchTimer = setTimeout(() => searchVehicles(value), 300);
};
const handleVehicleFocus = () => {
  if (vehicleOptions.value.length === 0) searchVehicles();
};

// 装车弹窗
const showLoadModal = ref(false);
const loadSubmitting = ref(false);
const useTempVehicle = ref(false);
const loadForm = reactive<{
  vehicleId?: number;
  vehicleNo?: string;
  driverName?: string;
  driverPhone?: string;
  remark?: string;
  loadedAt?: Dayjs | null;
}>({
  vehicleId: undefined,
  vehicleNo: "",
  driverName: "",
  driverPhone: "",
  remark: "",
  loadedAt: dayjs(),
});
const pendingIds = ref<number[]>([]);

const openLoadModal = (ids: number[]) => {
  if (!ids || ids.length === 0) {
    message.warning("请勾选需要装车的订单");
    return;
  }
  pendingIds.value = ids;
  useTempVehicle.value = false;
  loadForm.vehicleId = undefined;
  loadForm.vehicleNo = "";
  loadForm.loadedAt = dayjs();
  showLoadModal.value = true;
};
const closeLoadModal = () => {
  showLoadModal.value = false;
};

const confirmLoad = async () => {
  if (!pendingIds.value.length) {
    message.warning("未选择订单");
    return;
  }
  if (!useTempVehicle.value && !loadForm.vehicleId) {
    message.warning("请选择公司车辆");
    return;
  }
  if (useTempVehicle.value && !loadForm.vehicleNo) {
    message.warning("请输入临时车辆标识");
    return;
  }
  if (useTempVehicle.value && !loadForm.driverName) {
    message.warning("请输入车主姓名");
    return;
  }
  if (useTempVehicle.value && !loadForm.driverPhone) {
    message.warning("请输入车主联系电话");
    return;
  }

  loadSubmitting.value = true;
  try {
    const payload: any = { ids: pendingIds.value };
    if (useTempVehicle.value) {
      payload.vehicleNo = loadForm.vehicleNo;
      payload.driverName = loadForm.driverName;
      payload.driverPhone = loadForm.driverPhone;
      if (loadForm.remark) payload.remark = loadForm.remark;
    } else {
      payload.vehicleId = loadForm.vehicleId;
    }
    if (loadForm.loadedAt)
      payload.loadedAt = (loadForm.loadedAt as Dayjs).format(
        "YYYY-MM-DD HH:mm:ss"
      );

    const res = await orderLoad(payload);
    const data = res.data as any;
    message.success(
      `装车完成：成功${data.success || 0}，跳过${data.skipped || 0}`
    );
    showLoadModal.value = false;
    selectedRowKeys.value = [];
    fetchOrderList();
  } catch (e: any) {
    message.error(e?.message || "装车失败");
  } finally {
    loadSubmitting.value = false;
  }
};

const confirmUnload = async (ids: number[]) => {
  if (!ids || ids.length === 0) {
    message.warning("请勾选需要卸车的订单");
    return;
  }
  try {
    const res = await orderUnload({ ids });
    const data = res.data as any;
    message.success(
      `卸车完成：成功${data.success || 0}，跳过${data.skipped || 0}`
    );
    selectedRowKeys.value = [];
    fetchOrderList();
  } catch (e: any) {
    message.error(e?.message || "卸车失败");
  }
};

onMounted(async () => {
  await Promise.all([loadSites(), searchVehicles()]);
  fetchOrderList();
});
</script>

<style scoped>
.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.order-no {
  font-weight: 600;
  color: var(--primary-color);
}
.order-meta {
  font-size: 12px;
  color: var(--text-secondary);
}
.site-route {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-primary);
}
.site-arrow {
  color: var(--text-secondary);
}
.vehicle-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.hint {
  color: var(--text-secondary);
}
</style>
